import Vue from 'vue'
import store from '@/store/index'
import VueRouter from 'vue-router'
import Login from '@/views/login/index.vue'
import Layout from '@/views/layout'
import Dashboard from '@/views/dashboard'
import Article from '@/views/article'
Vue.use(VueRouter)

const routes = [
  { path: '/login', component: Login },
  {
    path: '/',
    component: Layout,
    redirect: '/dashboard',
    children: [
      { path: 'dashboard', component: Dashboard },
      { path: 'article', component: Article }
    ]
  }
]

const router = new VueRouter({
  routes
})
const whiteList = ['/login']
// 利用路由守卫进行登录拦截
router.beforeEach((to, from, next) => {
  // 根据有没有token来判断是否登录了
  const token = store.state.user.token
  // 1. 有token 直接放行
  if (token) {
    next()
    return
  }
  // 没有token判断去的是白名单中的页面直接放行
  if (whiteList.includes(to.path)) {
    next()
    return
  }
  next('/login')
})

export default router
